    //
//  chadViewController.m
//  CHAD
//
//  Created by Robin Mahony on 11-02-17.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

/*	
 Revision History: 
 
 Date     Author       Version   Changes
 ======== ============ ========= ================================================================
 02/18/11 Robin Mahony 1.0		Initial version.
 04/7/11  Robin Mahony 2.0		Added "backToMenuView" function, and removed "startApp" function since
								it is not needed.
 ======== ============ ========= ================================================================
 
 */

#import "chadViewController.h"

#import "CHADAppDelegate.h"
#import "ActiveView.h"
#import "MenuView.h"
#import <SystemConfiguration/SystemConfiguration.h>
#include <netdb.h>


// Padding for margins
#define kLeftMargin			5.0
#define kTopMargin			65.0
#define kRightMargin		-40.0
#define kInfoHeight		40.0


@implementation chadViewController

@synthesize menuView, myDelegate, activeView, moviePlayer;

/*- (void)startApp{
	NSLog(@"start button pressed");
	//add the main, active view

	//[[self view] addSubview:activeView];
	
}*/

- (void)backToMenuView{
	NSLog(@"back to menu view");
	[self.activeView disconnectSocket];
	
	//[moviePlayer unloadPlayer];
	
	//[[[UIApplication sharedApplication] keyWindow] removeFromSuperview:self.activeView];
	[activeView removeFromSuperview];
	//[[self view] addSubview:menuView];
	

}


- (BOOL)connectedToNetwork 
{
	/* Create zero addy.  */
    struct sockaddr_in zeroAddress;
    bzero(&zeroAddress, sizeof(zeroAddress));
    zeroAddress.sin_len = sizeof(zeroAddress);
    zeroAddress.sin_family = AF_INET;
    
    /* Recover reachability flags.  */
    SCNetworkReachabilityRef defaultRouteReachability 
	= SCNetworkReachabilityCreateWithAddress(NULL, (struct sockaddr *)&zeroAddress);
    SCNetworkReachabilityFlags flags;
    
    BOOL didRetrieveFlags = SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags);
    CFRelease(defaultRouteReachability);
    
    if (!didRetrieveFlags)
    {
        printf("Error. Could not recover network reachability flags\n");
		NSLog(@"not connected to internet");
        return NO;
    }
    
    BOOL isReachable = ((flags & kSCNetworkFlagsReachable) != 0);
    BOOL needsConnection = ((flags & kSCNetworkFlagsConnectionRequired) != 0);
	return (isReachable && !needsConnection) ? YES : NO;
}

/*
 Initializes active view and adds it to the MPMoviePlayer window
 */
-(void)initActiveView
{
	//initialize variables used in activeView
	self.activeView.exitFlag = 0;
	self.activeView.disconnectFlag = 0;
	
	[[self activeView] setTransform:CGAffineTransformMakeRotation(M_PI/2 )];
	[[self activeView] setTransform:CGAffineTransformTranslate(activeView.transform, 100, 70)];
	//[moviePlayer.view addSubview:self.activeView];
	//[moviePlayer.view bringSubviewToFront:self.activeView];
	//CHADAppDelegate.keyWindow.backgroundColor = [UIColor clearColor];
	//CHADAppDelegate.keyWindow.windowLevel = 2;
	[[[UIApplication sharedApplication] keyWindow] addSubview:self.activeView];
	[self.activeView connectToSocket]; //initialize socket for sending control data
	//[self.menuView removeFromSuperview];
	[self.activeView.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://142.58.172.188:8080/?action=stream"]]];
	//self.activeView.webView.opaque = NO;
	//self.activeView.webView.backgroundColor = [UIColor clearColor];
	//[menuView release]; //release menuView as it is no longer used
	
}

-(void)awakeFromNib{
	
	NSLog(@"entered awake from nib, chadViewController");
		
}

- (void) setDisconnectFlag{
	self.activeView.disconnectFlag = 1;
}

- (void) loadActiveView{
	
	NSLog(@"loading active view in view controller");
	//initialize variables used in activeView
	self.activeView.exitFlag = 0;
	self.activeView.disconnectFlag = 0;
	self.activeView.contCamFlag = 0;
	self.activeView.tactileOption = 1;
	
	//[[self activeView] setTransform:CGAffineTransformMakeRotation(M_PI/2 )];
	//[[self activeView] setTransform:CGAffineTransformTranslate(activeView.transform, 100, 70)];

	[self.activeView connectToSocket]; //initialize socket for sending control data
	[self.activeView connectToAudioSocket]; //initialize socket for sending audio
	
	
	
	//[menuView removeFromSuperview];
	//[menuView release];
	//self.menuView.hidden = TRUE;
	//self.activeView.hidden = FALSE;
	[self.activeView.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://telemedix.dyndns.org:8080/?action=stream"]]];
	[[self view] addSubview:activeView];
	
	//[self setView:activeView];
	
	//[menuView release]; //release menuView as it is no longer used
		
}

/*---------------------------------------------------------------------------
 * Method used to load movie player, that will load the live video stream
 *--------------------------------------------------------------------------*/
- (void)loadMoviePlayer
{  
	// Play movie from the bundle
	NSString *path = [[NSBundle mainBundle] pathForResource:@"Movie-1" ofType:@"mp4" inDirectory:nil];
	
	// Create custom movie player   
	moviePlayer = [[[CustomMoviePlayerViewController alloc] initWithPath:path] autorelease];
	//moviePlayer = [[[CustomMoviePlayerViewController alloc] initWithURL:@""] autorelease];
	
	
	// Show the movie player as modal
 	[self presentModalViewController:moviePlayer animated:YES];
	[[UIApplication sharedApplication] setStatusBarHidden:YES];

	// Prep and play the movie
	[moviePlayer readyPlayer];
	
	
	//add the controls to the movie player window
	[self initActiveView];
	
}




// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView {
	NSLog(@"loading menuView in loadView");
	[self setView:menuView];
	//self.activeView.hidden = TRUE;
	//[[self view] addSubview:activeView];
}

//Don't auto rotate - stay landscape
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
	
	if((interfaceOrientation == UIInterfaceOrientationLandscapeLeft) || (interfaceOrientation == UIInterfaceOrientationLandscapeRight))
		return YES;
	
	return NO;
}
/*- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation{
	//apparently 320 messes things up
	[activeView setFrame:CGRectMake(0, 0, 480, 320)];
	[activeView didRotateFromInterfaceOrientation:fromInterfaceOrientation];
}*/

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc. that aren't in use.
}

- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}


- (void)dealloc {
    [super dealloc];
}


@end
